import { getUserInfo } from "../../utils/storage"
import { createPeerCar, CreatePeerCarDto, createPeerImg } from '../../api/peerCar/index'
import { usingNature, energyNature } from '../../enums/car/index'
import config from '../../config/index'
import { getWxAppConfig } from '../../api/wxAppConfig/index'

Page({
  data: {
    carName: '',
    brand: '',
    price: 0,
    frameNumber: '',
    safeCount: 0,
    mileage: 0,
    registrationDate: '',
    homeLocation: '',
    emissionStandard: '',
    energy: null as number | null,
    insuranceDate: '',
    gearbox: '',
    annualInspection: '',
    location: '',
    usingNature: null as number | null,
    phone: '',
    description: '',
    regShow: false,
    insShow: false,
    annShow: false,
    usPopup: false,
    enPopup: false,
    usList: [] as string[],
    enList: [] as string[],
    usText: '',
    enText: '',
    fileList: [],
    urlList: [],
    user: {} as WxUser,
    wxAppConfig: {} as ListWxAppConfig,
    mixDate: new Date(2000, 0, 1).getTime()
  },
  afterRead(event: any) {
    const { file } = event.detail;
    let that = this
    wx.uploadFile({
      url: config.BaseUrl + '/api/upload/image',
      filePath: file.url,
      name: 'file',
      success: (res) => {
        if(res.statusCode === config.CREATED_CODE) {
          let fileRes = JSON.parse(res.data).data
          let fileList = []
          let urlList = []
          let fileStr = config.BaseUrl + '/' + fileRes.path
          fileList.push({...file, url: fileStr.replace(/\\/g, '/')})
          urlList.push(fileRes.path.replace(/\\/g, '/'))
          that.setData({
            fileList: this.data.fileList.concat(...fileList),
            urlList: this.data.urlList.concat(...urlList)
          })
        }
      }
    })
  },
  onRegDisplay() {
    this.setData({ regShow: true });
  },
  onInsDisplay() {
    this.setData({ insShow: true });
  },
  onAnnDisplay() {
    this.setData({ annShow: true });
  },
  onRegClose() {
    this.setData({ regShow: false });
  },
  onInsClose() {
    this.setData({ insShow: false });
  },
  onAnnClose() {
    this.setData({ annShow: false });
  }, 
  formatDate(date: Date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  onRegConfirm(event: any) {
    this.setData({
      regShow: false,
      registrationDate: this.formatDate(event.detail),
    });
    console.log(this.data.registrationDate);
  },
  onInsConfirm(event: any) {
    this.setData({
      insShow: false,
      insuranceDate: this.formatDate(event.detail),
    });
  },
  onAnnConfirm(event: any) {
    this.setData({
      annShow: false,
      annualInspection: this.formatDate(event.detail),
    });
  },
  onUsShow() {
    this.setData({
      usPopup: true
    })
  },
  onEnShow() {
    this.setData({
      enPopup: true
    })
  },
  onUsClose() {
    this.setData({
      usPopup: false
    })
  },
  onEnClose() {
    this.setData({
      enPopup: false
    })
  },
  onUsChange(event: any) {
    const { value } = event.detail
    let item = usingNature.find(item => item.label === value) as nature
    this.setData({
      usingNature: item.value,
      usText: item.label,
      usPopup: false
    })
  },
  onEnChange(event: any) {
    const { value } = event.detail
    let item = energyNature.find(item => item.label === value) as nature
    this.setData({
      energy: item.value,
      enText: item.label,
      enPopup: false
    })
  },
  async subData() {
    let data = {
      carName: this.data.carName,
      brand: this.data.brand,
      price: Number(this.data.price),
      frameNumber: this.data.frameNumber,
      safeCount: Number(this.data.safeCount),
      mileage: Number(this.data.mileage),
      registrationDate: this.data.registrationDate,
      homeLocation: this.data.homeLocation,
      emissionStandard: this.data.emissionStandard,
      energy: Number(this.data.energy),
      insuranceDate: this.data.insuranceDate,
      gearbox: this.data.gearbox,
      annualInspection: this.data.annualInspection,
      location: this.data.location,
      usingNature: Number(this.data.usingNature),
      phone: this.data.phone,
      description: this.data.description,
      userId: this.data.user.id
    } as CreatePeerCarDto
    wx.showLoading({title: '提交中'})
    const res = await createPeerCar(data)
    if(res.statusCode === config.CREATED_CODE) {
      if(this.data.urlList.length === 0) {
        wx.hideLoading()
        wx.showToast({title: '提交成功', icon: 'success'})
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }, 1000)
      } else {
        let peer = res.data as ListPeerCar
        this.data.urlList.forEach(item => {
          let data = {
            url: item,
            peerId: peer.id as string
          }
          createPeerImg(data).then((res) => {
            if(res.statusCode !== config.CREATED_CODE) {
              wx.showToast({title: '网络错误', icon: 'error'})
              return
            }
          })
        })
        wx.hideLoading()
        wx.showToast({title: '提交成功', icon: 'success'})
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }, 1000)
      }
    } else {
      wx.showToast({title: '网络错误', icon: 'error'})
    }
  },
  async initData() {
    const res = await getWxAppConfig()
    if(res.statusCode === config.SUCCESS_CODE) {
      this.setData({
        wxAppConfig: res.data as ListWxAppConfig
      })
    } else {
      wx.showToast({title: '网络错误', icon: 'error'})
    }
    const user = getUserInfo()
    let usList = [] as string[]
    let enList = [] as string[]
    usingNature.forEach(item => {
      usList.push(item.label)
    })
    energyNature.forEach(item => {
      enList.push(item.label)
    })
    this.setData({
      phone: user.phone,
      user,
      usList,
      enList
    })
  },
  onLoad() {
    this.initData()
  }
})